<?php
/**
 * 微信js-sdk
 * @author xiegaolei
 * 微信JS-SDK是微信公众平台面向网页开发者提供的基于微信内的网页开发工具包
 * 
 */

class Jssdk extends Wechat {
     
    /**
     * jsapi_ticket保存路径
     */
    private $jsapi_ticket_path  = './weixin/data/jsapi_ticket.json';
    
    /**
     * 构造方法，调用微信高级接口时实例化SDK
     * @param string $appid  微信appid
     * @param string $secret 微信appsecret
     */
    public function __construct($appid, $secret){
        parent::__construct($appid, $secret);
        //自定初始化
    }
    
    public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();
    
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
    
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    
        $signature = sha1($string);
    
        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }
    

    
    /**
     * 获取jsapi_ticket临时票据
     * [getJsApiTicket ]
     * @return unknown
     */
    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新
        $jsapi_ticket_file = $this->jsapi_ticket_path;
        $data = json_decode(file_get_contents($jsapi_ticket_file));
        if ($data->expire_time < time()) {
            $accessToken = $this->getAccessToken();
            // 如果是企业号用以下 URL 获取 ticket
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            $params = array(
                'type'           => 'jsapi',
                'access_token'   => $accessToken,
            );
            
            $url = $this->apiURL.'/ticket/getticket';
            $res = json_decode($this->http($url,$params));
            
            $ticket = $res->ticket;
            if ($ticket) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen($jsapi_ticket_file, "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }else{
				throw new Exception('错误code:'.$res->errcode.',错误：'.$res->errmsg);
			}
        } else {
            $ticket = $data->jsapi_ticket;
        }
    
        return $ticket;
    }
    
    /**
     * 生成随机串
     * [createNonceStr ]
     * @param number $length
     */
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }


}
